/**
 * Created by Ysssssss on 20/12/24.
 */
const app = getApp();
// import { uploadImage } from '../../../common/qiniu';
import { uploadImage } from '../../../common/cos';
import { arr2Obj, formatPrice } from '../../../common/utils';
import { PACKAGE_PRODUCT_PAGE } from '../../../constants/route';
import { PageOssMixins } from '../../../behaviors/page';
import { createProductGroupModalMixin } from '../../../behaviors/product';
import {
    getProductInfo,
    createProduct,
    editProduct,
    getProductGroupList,
    createProductGroup
} from '../../../api/product';
import { tipToast, navBack, navToAction } from '../../../common/env';

const _reformProductInfoToData = (product, data) => {
    let { cosConf } = data;
    let _data = {
        pics: (product.pics || []).map(pic => ({ url: `${cosConf.path}/${pic}` })),
        name: product.name,
        intro: product.intro,
        picIntros: (product.introPics || []).map(pic => ({ url: `${cosConf.path}/${pic}` })),
        group: product.productGroupId,
        attributeDefs: product.productAttributeDefs || [],
        price: '',
    }
    if (product.hasSpecs) {
        let skus = product.productSpecs.map(sku => ({
            ...sku,
            attributes: sku.productAttributes,
            id: sku.name
        }))
        _data = {
            ..._data,
            skus,
            skusRenderInfo: _reformSkusRender(skus),
            useSkus: 2
        }
    } else {
        _data = {
            ..._data,
            price: formatPrice(product.priceMin || product.priceMax, true),
            useSkus: 1
        }
    }
    return _data
}

const _reformDataToProductInfo = (data) => {
    let { cosConf } = data;
    let retProductInfo = {
        name: data.name,
        pics: data.pics.map(pic => pic.url.replace(`${cosConf.path}/`, '')),
        intro: data.intro,
        introPics: data.picIntros.map(pic => pic.url.replace(`${cosConf.path}/`, '')),
        productGroupId: data.group,
    }
    let { productSpecsMap, productAttributeDefsMap } = data._productInfo || {}
    if (data.useSkus === 1) {
        retProductInfo.price = formatPrice(data.price);
        if (!retProductInfo.productAttributeDefs) {
            retProductInfo.productAttributeDefs = [];
        }
        if (!retProductInfo.productSpecs) {
            retProductInfo.productSpecs = [{
                price: retProductInfo.price,
                productAttributes: [],
            }];
        }
    } else if (data.useSkus === 2) {
        retProductInfo.productSpecs = data.skus.map(sku => {
            let ret = {
                name: sku.id,
                productAttributes: sku.attributes,
                price: sku.price,
            }
            let _productSpecs = productSpecsMap ? productSpecsMap[ret.name] : null
            if (_productSpecs) {
                ret = {
                    ...ret,
                    productSpecId: _productSpecs.productSpecId,
                    remotePK: _productSpecs.remotePK
                }
            }
            return ret;
        })
        retProductInfo.productAttributeDefs = data.attributeDefs.map(attr => {
            let _productAttributeDefs = productAttributeDefsMap ? productAttributeDefsMap[attr.key] : null
            return _productAttributeDefs ? {
                ...attr,
                remotePK: _productAttributeDefs.remotePK
            } : {
                ...attr
            }
        })
    }
    return retProductInfo
}

const _reformSkusRender = (skus) => {
    if (!skus.length) {
        return {
            name: '',
            price: '',
        }
    }
    let minPrice = Infinity
    let maxPrice = -Infinity
    let names = skus.map(sku => {
        minPrice = Math.min(minPrice, sku.price)
        maxPrice = Math.max(maxPrice, sku.price)
        return sku.id
    })
    return {
        name: names.join(', '),
        price: minPrice === maxPrice ? formatPrice(minPrice, true) : `${formatPrice(minPrice, true)}-${formatPrice(maxPrice, true)}`
    }
}

Page({
    mixins: [createProductGroupModalMixin, PageOssMixins],
    data: {
        name: '',
        price: '',
        intro: '',
        picIntros: [],
        useSkus: '',
        attributeDefs: [],
        skus: [],
        skusRenderInfo: {},
        group: '',

        skusColumns: [{
            id: 1,
            name: '无规格'
        }, {
            id: 2,
            name: '多规格'
        }],
        pics: [],
        groupList: [],
        groupMap: {},
        pickerVisible: {},
        errorInfo: {},
        _productInfo: {}
    },

    async onLoad(option) {
        app.event.addListener('productSkusChange', this._productSkusChange.bind(this))
        const { id } = option || {}
        if (id) {
            const res = await getProductInfo({ id })
            const groupList = await getProductGroupList()
            this.setData({
                ..._reformProductInfoToData(res, this.data),
                _productInfo: {
                    ...res,
                    productSpecsMap: arr2Obj(res.productSpecs || [], 'name'),
                    productAttributeDefsMap: arr2Obj(res.productAttributeDefs || [], 'key')
                },
                groupList: groupList,
                groupMap: arr2Obj(groupList, 'productGroupId'),
            })
        } else {
            const groupList = await getProductGroupList()
            this.setData({
                groupList: groupList,
                groupMap: arr2Obj(groupList, 'productGroupId'),
            })
        }
    },

    onUnload: function () {
        app.event.removeListener('productSkusChange', this._productSkusChange.bind(this))
    },

    _productSkusChange({ properties, standardList }) {
        const { errorInfo } = this.data
        this.setData({
            attributeDefs: properties,
            skus: standardList,
            skusRenderInfo: _reformSkusRender(standardList),
            errorInfo: {
                ...errorInfo,
                skus: undefined
            }
        })
    },

    handleFormChange(e) {
        const { errorInfo } = this.data
        const { key } = e.currentTarget.dataset
        let value = e.detail;
        if (key === 'price') {
            value = formatPrice(value)
            value = formatPrice(value, true)
        }
        this.setData({
            [key]: value,
            errorInfo: {
                ...errorInfo,
                [key]: undefined
            }
        })
    },

    handlePickerShow(e) {
        const { pickerVisible } = this.data
        const { key } = e.currentTarget.dataset
        this.setData({
            pickerVisible: {
                ...pickerVisible,
                [key]: true
            },
        })
    },

    handlePickerHide(e) {
        const { pickerVisible } = this.data
        const { key } = e.currentTarget.dataset
        this.setData({
            pickerVisible: {
                ...pickerVisible,
                [key]: false
            },
        })
    },

    handlePickerChange(e) {
        const { errorInfo } = this.data
        const { key } = e.currentTarget.dataset
        this.setData({
            [key]: e.detail.value.id || e.detail.value.productGroupId,
            errorInfo: {
                ...errorInfo,
                [key]: undefined
            }
        })
    },

    async createGroup(e) {
        const { pickerVisible } = this.data
        const value = e.detail
        if (value) {
            let res = await createProductGroup({ name: value })
            if (!res) return;
            const groupList = await getProductGroupList()
            app.event.trigger('productGroupListChange', groupList)
            const group = groupList.slice(-1)[0]
            this.setData({
                createModalVisible: false,
                group: group.productGroupId,
                groupList: groupList,
                groupMap: arr2Obj(groupList, 'productGroupId'),
                pickerVisible: {
                    ...pickerVisible.group,
                    group: false
                }
            })
        } else {
            tipToast('请输入分组名称')
        }
    },

    goSkusEditPage() {
        const { skus, attributeDefs } = this.data
        navToAction(PACKAGE_PRODUCT_PAGE['productProperty'], {}, {
            success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                res.eventChannel.emit(
                    'acceptDataFromOpenerPage',
                    {
                        standardPriceMap: arr2Obj(skus, 'id', 'price'),
                        properties: attributeDefs
                    }
                )
            }
        })
    },

    afterRead(event) {
        const { key } = event.currentTarget.dataset
        const { file } = event.detail;
        let { cosConf } = this.data;
        uploadImage('product', file).then(res => {
            const { url } = res
            url && this.setData({
                [key]: [
                    ...this.data[key],
                    {
                        url: `${cosConf.path}/${url}`
                    }
                ]
            })
        })
    },

    deleteFile(event) {
        const { key } = event.currentTarget.dataset
        const { index } = event.detail
        this.setData({
            [key]: [
                ...this.data[key].slice(0, index),
                ...this.data[key].slice(index + 1)
            ]
        })
    },

    async handleSubmit() {
        const { pics, name, price, useSkus, skus, intro, picIntros, _productInfo } = this.data
        let errorInfo = {}
        if (name === '') {
            errorInfo.name = ''
        }
        if (useSkus !== 2 && price === '') {
            errorInfo.price = ''
        } else if (useSkus !== 2 && isNaN(price)) {
            errorInfo.price = '请输入数字'
        }
        if (useSkus === '') {
            errorInfo.useSkus = ''
        }
        if (useSkus === 2 && (!skus || !skus.length)) {
            errorInfo.skus = '请设置规格'
        }
        if (JSON.stringify(errorInfo) === '{}') {
            let params = _reformDataToProductInfo(this.data);
            let res = null
            if (_productInfo.productId) {
                params = {
                    ...params,
                    id: _productInfo.productId,
                    remotePK: _productInfo.remotePK
                }
                res = await editProduct(params)
            } else {
                res = await createProduct(params)
            }
            if (!res) return;
            app.event.trigger('productEdit')
            navBack()
        } else {
            this.setData({
                errorInfo
            })
        }
    }
})